package com.lanyou.esb.web.serviceMonitor;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.service.CookProxyServiceTimeService;
import com.lanyou.esb.service.QuantityAnalysisService;
import com.lanyou.esb.vo.ServiceAnalysisVo;

/**
 * 流量分析控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/quantityAnalysis")
public class QuantityAnalysisController {
	@Autowired
	UserSessionService userSessionService;
	@Autowired
	private QuantityAnalysisService quantityAnalysisService;
	@Autowired
	private CookProxyServiceTimeService cookProxyServiceTimeService;
	/** 延时读取服务数据时间 **/
	private static int LAZY_TIME = Constants4Redis.QUANTITY_ANALYSIS_INTERNAL_TIME * 2;
	/** 读取数据区间个数 **/
	private static int SIZE = 20;

	/**
	 * 查找EBS总量分析信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/findQuantityAnalysisInfo", produces = "application/json")
	public String findQuantityAnalysisInfo() {
		Map<String, Object> result = new HashMap<>(2);
		Date serviceTime = new Date();
		try {
			// 获取COOKPROXY服务器时间
			Calendar calendar = cookProxyServiceTimeService
					.getCookProxyServiceTime();
			if (calendar != null) {
				serviceTime = calendar.getTime();
			}
		} catch (Exception e) {
			serviceTime = new Date();
		}
		// 设置时间为统计时间间隔的整数倍 start===================
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(serviceTime);
		calendar.add(Calendar.SECOND, -calendar.get(Calendar.SECOND)
				% Constants4Redis.QUANTITY_ANALYSIS_INTERNAL_TIME);
		// 为避免有些数据未能及时写入REDIS，设置统计时间为：服务器时间-时间间隔*2
		calendar.add(Calendar.SECOND, -LAZY_TIME);
		serviceTime = calendar.getTime();
		// 设置时间为统计时间间隔的整数倍 end===================
		try {
			ServiceAnalysisVo vo = quantityAnalysisService
					.findQuantityAnalysisInfo(serviceTime, SIZE);
			// 对结果进行排序
			vo.sort();
			// 最后一个区间总量时间点
			result.put(
					CommonUtils.MSG_FIELD_LEFTDATE,
					(vo.getTotals().size() > 0) ? vo.getTotals()
							.get(vo.getTotals().size() - 1).getKey() : 0l);
			// 最后一个区间总量数据
			result.put(CommonUtils.MSG_FIELD_LEFTVALUE4TOTAL, (vo.getTotals()
					.size() > 0) ? vo.getTotals()
					.get(vo.getTotals().size() - 1).getValue() : 0l);
			// 最后一个区间成功数
			result.put(
					CommonUtils.MSG_FIELD_LEFTVALUE4S,
					(vo.getSuccess().size() > 0) ? vo.getSuccess()
							.get(vo.getSuccess().size() - 1).getValue() : 0l);
			// 最后一个区间失败数
			result.put(
					CommonUtils.MSG_FIELD_LEFTVALUE4F,
					(vo.getFailures().size() > 0) ? vo.getFailures()
							.get(vo.getFailures().size() - 1).getValue() : 0l);
			result.put(CommonUtils.MSG_FIELD_TOTAL, vo.getTotals());
			result.put(CommonUtils.MSG_FIELD_SUCCESS, vo.getSuccess());
			result.put(CommonUtils.MSG_FIELD_FAILURES, vo.getFailures());
			result.put(CommonUtils.MSG_FIELD_RESULT, true);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);
	}

	/**
	 * 查找平台流量最新信息
	 * 
	 * @param leftDate
	 *            ：上次读数时间
	 * @param leftValue4Total
	 *            ：上次平台总流量的读数
	 * @param leftValue4S
	 *            ：上次成功次数的读数
	 * @param leftValue4F
	 *            ：上次失败次数的读数
	 * @return
	 */
	@RequestMapping(value = "/getLatestQuantityInfo", produces = "application/json")
	public String getLatestQuantityInfo(String leftDate,
			String leftValue4Total, String leftValue4S, String leftValue4F) {
		// 区间右侧时间点
		Date rightDate = null;
		// 区间左侧时间点
		Date lastDate = null;
		// 区间内已读的流量
		long valueL = 0l;
		// 区间内已读的请求成功数
		long valueLS = 0l;
		// 区间内已读的请求失败数
		long valueLF = 0l;
		try {
			// 设置区间左侧时间
			long value = Long.parseLong(leftDate);
			lastDate = new Date(value);
			// 设置区间右侧时间，默认为区间左侧时间+5秒
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(lastDate);
			calendar.add(Calendar.SECOND,
					Constants4Redis.QUANTITY_ANALYSIS_INTERNAL_TIME);
			rightDate = calendar.getTime();
		} catch (Exception e) {
			lastDate = new Date();
			rightDate = lastDate;
		}
		// 设置区间内已读的总流量
		try {
			valueL = Long.parseLong(leftValue4Total);
		} catch (Exception e) {
			valueL = 0l;
		}
		// 设置区间内已读的请求成功数
		try {
			valueLS = Long.parseLong(leftValue4S);
		} catch (Exception e) {
			valueLS = 0l;
		}
		// 设置区间内已读的请求失败数
		try {
			valueLF = Long.parseLong(leftValue4F);
		} catch (Exception e) {
			valueLF = 0l;
		}
		// 结果
		Map<String, Object> result = new HashMap<>(2);
		try {
			// 查询时间区间内未读的流量信息
			result = quantityAnalysisService.getLatestQuantityInfo(valueL,
					valueLS, valueLF, lastDate, rightDate);
			result.put(CommonUtils.MSG_FIELD_KEY, rightDate.getTime());
			result.put(CommonUtils.MSG_FIELD_LEFTDATE, rightDate.getTime());
			result.put(CommonUtils.MSG_FIELD_LEFTDATE4SF, rightDate.getTime());
			result.put(CommonUtils.MSG_FIELD_RESULT, true);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);
	}
}
